package business

import (
	"errors"
	"vueBasic/app/admin/filter"
	"vueBasic/app/common/model"
	"vueBasic/extend/conv"
)

var RoleB = new(roleBus)

type roleBus struct {
}

func (*roleBus) GetPageList(req *filter.AdminRoleReq) ([]*filter.AdminRoleListRes, int64, error) {

	where := "1=1"
	if !conv.IsEmpty(req.Title) {
		where += " AND title like '%" + req.Title + "%'"
	}

	if !conv.IsEmpty(req.Status) {
		where += " AND status = " + conv.String(req.Status)
	}

	list, count, err := model.RoleM.GetList(where, req.Page, req.Limit)
	return list, count, err
}

func (*roleBus) Add(req *filter.AdminRoleAddReq) (uint, error) {
	//判断该角色是否存在
	checkRole, _ := model.RoleM.GetRoleByTitle(req.Title)
	if checkRole != nil {
		return 0, errors.New("角色名称已存在！")
	}
	res, err := model.RoleM.Add(req)
	if err != nil {
		return 0, err
	}
	return res, nil
}

func (*roleBus) GetUpdateInfo(req *filter.AdminRoleGetUpdateInfoReq) (map[string]interface{}, error) {
	data := make(map[string]interface{}, 0)
	info, err := model.RoleM.GetRoleById(req)
	if err != nil {
		return nil, errors.New("角色不存在")
	}
	access := model.RoleAccessM.GetValueByRoleId(conv.Int(req.Id), 1)
	//获取module_id
	module_ids := model.AccessM.GetColumnByIds(access, "module_id")
	uniqueAccess := conv.RemoveCommonElements(access, module_ids) //去掉两个相同的元素，主要是去掉父元素
	data["info"] = info
	data["access"] = uniqueAccess
	return data, nil
}

func (*roleBus) Update(req *filter.AdminRoleUpdateReq) (uint, error) {
	res, err := model.RoleM.Update(req)
	if err != nil {
		return 0, errors.New("更新失败")
	}
	return res, nil
}

func (*roleBus) UpdateExt(req map[string]interface{}) error {
	if conv.Int(req["id"]) == 9 {
		return errors.New("超级管理员禁止操作")
	}
	err := model.RoleM.UpdateExt(req)
	if err != nil {
		return errors.New("更新失败")
	}
	return nil
}

func (*roleBus) Delete(req *filter.AdminRoleDeleteReq) (uint, error) {
	ids := conv.Slice(req.Id)
	if len(ids) > 1 {
		return 0, errors.New("禁止批量删除")
	}
	if conv.Int(req.Id) == 9 {
		return 0, errors.New("超级管理员禁止删除")
	}
	res, err := model.RoleM.Delete(ids)
	if err != nil {
		return 0, errors.New("删除失败")
	}
	return res, nil
}

func (b *roleBus) DoAuth(req *filter.AdminRoleAuthReq) error {

	//删除
	dErr := model.RoleAccessM.Delete(req.Id)
	if dErr != nil {
		return errors.New("授权失败(1)")
	}
	roleAccess := make([]*filter.AdminRoleAccessReq, 0)
	for _, v := range req.Access {
		roleAccess = append(roleAccess, &filter.AdminRoleAccessReq{
			RoleId:   req.Id,
			AccessId: conv.Int(v),
		})
	}
	err := model.RoleAccessM.Add(roleAccess)
	if err != nil {
		return errors.New("授权失败(2)")
	}
	return nil
}
